package com.itheima.pay.service.impl;

import com.github.wxpay.sdk.WXPayUtil;
import com.itheima.pay.dto.Result;
import com.itheima.pay.service.WxPayService;
import com.itheima.pay.util.HttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WxPayServiceImpl implements WxPayService {

    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.partner}")
    private String partner;
    @Value("${weixin.partnerKey}")
    private String partnerKey;
    @Value("${weixin.notifyUrl}")
    private String notifyUrl;

    /**
     * 获取二维码
     */
    @Override
    public Map<String,String> createNative(Map<String,String> parameterMap) {
        // 参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", appId);
        paramMap.put("mch_id", partner);
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        paramMap.put("sign", "");
        paramMap.put("body", "微信支付商城测试");
        paramMap.put("spbill_create_ip", "127.0.0.1");
        paramMap.put("notify_url", notifyUrl);
        paramMap.put("trade_type", "NATIVE");
        paramMap.put("out_trade_no", parameterMap.get("outTradeNo"));
        paramMap.put("total_fee", parameterMap.get("totalFee"));
        // map转xml字符串，可以携带签名
        try {
            String xml = WXPayUtil.generateSignedXml(paramMap, partnerKey);
            // url地址
            String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            HttpClient httpClient = new HttpClient(url);
            // 提交方式
            httpClient.setHttps(true);
            // 提交参数
            httpClient.setXmlParam(xml);
            httpClient.post();
            // 获取返回的数据
            String result = httpClient.getContent();
            // 返回数据转map
            return WXPayUtil.xmlToMap(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 沙箱环境
     */
    @Override
    public Map<String, String> shaxiang() {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("mch_id", "1305638280");
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        paramMap.put("sign", "5K8264ILTKCH16CQ2502SI8ZNMTM67VS");
        try {
            //String xml = WXPayUtil.generateSignedXml(paramMap, partnerKey);
            String url = "https://api.mch.weixin.qq.com/xdc/apiv2getsignkey/sign/getsignkey";
            HttpClient httpClient = new HttpClient(url);
            // 提交方式
            httpClient.setHttps(true);
            // 提交参数
            httpClient.setParameter(paramMap);
            httpClient.post();
            // 获取返回的数据
            String result = httpClient.getContent();
            return WXPayUtil.xmlToMap(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
